<?php

class ContentController extends BackendController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

    public function actions()
    {
        return array(
            'fileUpload'=>array(
                'class'=>'ext.redactor.actions.FileUpload',
                'uploadPath'=>'uploads/files',
                'uploadUrl'=>Yii::app()->getBaseUrl(true).'/uploads/files',
                'uploadCreate'=>true,
                'permissions'=>0755,
            ),
            'imageUpload'=>array(
                'class'=>'ext.redactor.actions.ImageUpload',
                'uploadPath'=>'uploads/imgs',
                'uploadUrl'=>Yii::app()->getBaseUrl(true).'/uploads/imgs', //'/url/to/uploads/folder',
                'uploadCreate'=>true,
                'permissions'=>0755,
            ),
            'imageList'=>array(
                'class'=>'ext.redactor.actions.ImageList',
                'uploadPath'=>'uploads/imgs',
                'uploadUrl'=>'/uploads/imgs', //'/url/to/uploads/folder',
            ),
        );
    }
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		if(empty($_GET['type']))
            throw new CHttpException(500, 'content type is missing');
        
        $modelName = CommonHelper::getModelName($_GET['type']);
        $model = new $modelName;
        $model->user_id = 'system_user';
        
		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);
        $className = get_class($model);
		if(isset($_POST[$className]))
		{
			$model->attributes=$_POST[$className];
            
            if($model instanceof OneChoice)
                $this->_beforeOneChoiceSave($model);
            
			if($model->save())
            {
                if(Yii::app()->request->getIsAjaxRequest())
                {
                    exit (json_encode(array(
                        'result'=>true,
                        'data'=>array(
                            'url' => $this->createAbsoluteUrl('content/view/', array('id'=>$model->id)),
                        ),
                    )));
                }
                else
                    $this->redirect(array('view','id'=>$model->id));
            }
            else
            {
                if(Yii::app()->request->getIsAjaxRequest())
                {
                    exit (json_encode(array(
                        'result'=>false,
                        'errors'=>$model->getErrors(),
                    )));
                }
            }
		}
        
		$this->render('create',array(
			'model'=>$model,
		));
	}
    
    protected function _beforeOneChoiceSave(OneChoice $model)
    {
        $_choices = array();
        if( is_array($model->choices) && ! empty($model->choices))
        {
            foreach($model->choices as $choice)
            {
                if( ! empty($choice) && is_array($choice))
                {
                    if( ! empty($choice['answer']))
                        $choice['answer'] = true;
                    else
                        $choice['answer'] = false;
                    
                    $_choice = new Choice();
                    $_choice->setAttributes($choice);
                    if($_choice->validate())
                        $_choices[] = $_choice;
                }
            }

            if( ! empty($_choices))
                $model->setChoices($_choices);
        }
    }

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);
        $className = get_class($model);
//        var_dump($_POST[$className]);
//        exit;
		if(isset($_POST[$className]))
		{
			$model->attributes=$_POST[$className];
            
            if($model instanceof OneChoice)
                $this->_beforeOneChoiceSave($model);
            
			if($model->save())
            {
                if(Yii::app()->request->getIsAjaxRequest())
                {
                    exit (json_encode(array(
                        'result'=>true,
                        'data'=>array(
                            'url' => $this->createAbsoluteUrl('content/view/', array('id'=>$model->id)),
                        ),
                    )));
                }
                else
                    $this->redirect(array('view','id'=>$model->id));
            }
            else
            {
                if(Yii::app()->request->getIsAjaxRequest())
                {
                    exit (json_encode(array(
                        'result'=>false,
                        'errors'=>$model->getErrors(),
                    )));
                }
            }
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
//	public function actionIndex()
//	{
//		$dataProvider=new EMongoDocumentDataProvider('ItemType');
//		$this->render('index',array(
//			'dataProvider'=>$dataProvider,
//		));
//	}

	/**
	 * Manages all models.
	 */
	public function actionIndex()
	{
		$model = new Content('search');
        $this->layout = '//layouts/column2';
        
		$model->unsetAttributes();  // clear any default values
        $model->setDbCriteria(array('sort'=>array('ctime'=>EMongoCriteria::SORT_DESC)));
		if(isset($_GET['Content']))
        {
            $conditions = array();
            foreach($_GET['Content'] as $k => $v)
            {
                $v = trim($v);
                if( ! empty($v))
                    $conditions[$k] = array('$regex'=>'.*' . $v . '.*', '$options'=>'i');
            }    
            
            $criteria = new EMongoCriteria;
            if( ! empty($conditions))
                $criteria->setConditions($conditions);
            
            $dataProvider = new EMongoDocumentDataProvider('Content', array('criteria'=>$criteria));
        }
        else
            $dataProvider = new EMongoDocumentDataProvider($model);
        
		$this->render('index',array(
			'model'=>$model,
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Content::model()->findByPk(new MongoId($id));
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='content-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
